import store from "store";
import $ from "jquery";
import loading from "../entry/components/loading";
import "./oldcommon/layer"

let com = {};
let basePath = "http://api.keniuweb.cn";

com.getdb = function (key) {
  return store.get(key);
}
com.savedb = function (key, val) {
  store.set(key, val)
}

com.ajax = function (obj) {
  loading.mask();
  $.ajax({
    url: basePath + obj.url,
    data: obj.data ? obj.data : "",
    method: obj.method == undefined ? "get" : obj.method,
    xhrFields: {
      withCredentials: true
    },
    crossDomain: true,
  })
    .done(function (data) {
      obj.ok(data);
      loading.unmask();
    })
    .fail(function (data) {
      loading.unmask();
      if(data.status==401){
        window.location="/dist/index.html"
      }
      if (obj.fail instanceof Object) {
        obj.fail(data);
      } else {
        console.log(data);
      }
    });
  return this;
};

com.CheckMobile = function (mobile) {
  if (!/^1[34578]\d{9}$/.test(mobile)) {
    return false;
  } else {
    return true;
  }
};

com.UploadFile = function (form, cab) {
  $.ajax({
    type: "post",
    url: "//openapi.keniu.site/uploadfiles",
    data: form,
    processData: false,
    contentType: false,
    async: true,
    // 下面三个参数要指定，如果不指定，会报一个JQuery的错误
    cache: false,
    success: function (data) {
      cab(data);
    }
  });
};
com.UploadOneFile = function (form, cab) {
  $.ajax({
    type: "post",
    url: "//openapi.keniu.site/uploadfile",
    data: form,
    processData: false,
    contentType: false,
    async: true,
    // 下面三个参数要指定，如果不指定，会报一个JQuery的错误
    cache: false,
    success: function (data) {
      cab(data);
    }
  });
};

//获取url中的参数
com.getUrlParam = function (name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数
  if (r != null) return unescape(r[2]);
  return null; //返回参数值
};

com.alertDialog = function(content){
  console.log(layer);
  layer.open({
    content: content
    ,btn: ['确定']
    ,yes: function(index){
      layer.close(index);
    }
  });
}
com.showCenter =  function (ele) {
  ele.show();
  let eleHeight = ele.height();
  ele.css({"margin-top": -eleHeight / 2 + "px","top":"50%"});
}

com.saveSuc = function (url, editUrl) {
  layer.open({
    content: '活动保存成功,如果您使用有任何疑问，请致电：0571-88613816。',
    btn: ['马上去看一下', '留下继续编辑'],
    yes: function (index) {
      layer.close(index);
      window.location = url
    },
    no: function (index) {
      layer.close(index);
      window.location = editUrl
    },
  });
};
export default com;
